package com.dj.product.k2faas.converter;

import jakarta.persistence.AttributeConverter;
import com.dj.product.k2faas.common.utils.BeanUtil;
import com.dj.product.k2faas.common.utils.JsonUtil;

import static org.apache.commons.lang3.StringUtils.isBlank;

/**
 * Created by 丁建 on 2025/9/23 08:39
 *
 * @author 丁建
 */
public abstract class AbstractNullableObjectConverter<X> implements AttributeConverter<X, String> {
    @Override
    public String convertToDatabaseColumn(X object) {
        if (object == null) {
            return "{}";
        }
        return JsonUtil.toJSON(object);
    }

    @Override
    public X convertToEntityAttribute(String s) {
        if (isBlank(s)) {
            return BeanUtil.construct(getClazz());
        }
        return JsonUtil.toObject(s, getClazz());
    }

    protected abstract Class<X> getClazz();

}
